package org.yate.oa.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.yate.oa.model.LoginEntity;
import org.yate.oa.model.OrgEntity;
import org.yate.oa.model.RelationEntity;
import org.yate.oa.model.RestDayEntity;
import org.yate.oa.model.UserEntity;
import org.yate.oa.service.IRelationService;
import org.yate.oa.service.IRestDayService;
import org.yate.oa.service.IUserService;
import org.yate.oa.service.imp.OrgService;
import org.yate.oa.service.imp.RelationService;
import org.yate.oa.service.imp.RestDayService;
import org.yate.oa.service.imp.UserService;
import org.yate.oa.utils.Constants;
import org.yate.oa.utils.MessageDigestUtils;

import com.alibaba.fastjson.JSONObject;

@WebServlet(urlPatterns = { "/user/get", "/user/post", "/user/put", "/user/delete" }, asyncSupported = false)
public class UserController extends BaseServletController {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setCharacterEncoding("utf-8");
		res.setContentType("text/html; charset=utf-8");
		req.setCharacterEncoding("utf-8");
		String reqType = req.getParameter("type");
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		if (StringUtils.isEmpty(reqType)) {
			json.put("code", "401");
			json.put("msg", "type cannot be null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		if (reqType.equals("add")) {
			addUser(req, res);
		} else if (reqType.equals("delete")) {
			deleteUser(req, res);
		} else if (reqType.equals("getall")) {
			getAllUsers(req, res);
		} else if (reqType.equals("getChildrenOrd")) {
			getAllUsersByOrgId(req, res);
		} else if (reqType.equals("modifypassword")) {
			modifyPassword(req, res);
		} else if (reqType.equals("modifyuser")) {
			modifyUser(req, res);
		} else if (reqType.equals("get")) {
			get(req, res);
		} else if (reqType.equals("resetpwd")) {
			resetPassword(req, res);
		} else if (reqType.equals("copyto")) {
			copyTo(req, res);
		} else if (reqType.equals("removeout")) {
			removeOut(req, res);
		}
	}

	private void get(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer id = Integer.parseInt(req.getParameter("userId"));
		UserEntity e = new UserEntity();
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		e = usersvr.getEntity(id);
		json.put("code", "200");
		json.put("data", e);
		out.println(json);
		out.flush();
		out.close();
	}

	private void addUser(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		String email = req.getParameter("email");
		String password = "123456";
		String trueName = req.getParameter("trueName");
		Integer orgId = Integer.parseInt(req.getParameter("orgId"));
		String remark = req.getParameter("remark");
		if (StringUtils.isEmpty(email) || StringUtils.isEmpty(trueName) || orgId < 0) {
			json.put("code", "401");
			json.put("msg", "email or truename, orgid cannot be null");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		UserEntity e = new UserEntity(0, email, MessageDigestUtils.toMD5Hex(password), trueName, remark);
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		usersvr.addUser(e);
		IRelationService relationSvr = this.springCtx.getBean(RelationService.class);
		RelationEntity re = new RelationEntity();
		re.setOrgId(orgId);
		re.setUserId(e.getId());
		relationSvr.add(re);
		IRestDayService restSvr = this.springCtx.getBean(RestDayService.class);
		restSvr.add(new RestDayEntity(e, Double.valueOf("0"), Double.valueOf("0")));
		json.put("code", "200");
		json.put("msg", "add user succsss");
		out.println(json);
		out.flush();
		out.close();

	}

	private void copyTo(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer userId = Integer.parseInt(req.getParameter("userId"));
		Integer orgId = Integer.parseInt(req.getParameter("orgId"));
		if (userId <= 0 || orgId <= 0) {
			json.put("code", "401");
			json.put("msg", "param error");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		RelationEntity re = new RelationEntity(userId, orgId);
		IRelationService svr = this.springCtx.getBean(IRelationService.class);
		if (svr.getEntityBy(re) == null) {
			svr.add(re);
			json.put("code", "200");
			json.put("msg", "move success");
			out.println(json);
			out.flush();
			out.close();
		} else {
			json.put("code", "401");
			json.put("msg", "数据重复");
			out.println(json);
			out.flush();
			out.close();
			return;
		}

	}

	private void removeOut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer userId = Integer.parseInt(req.getParameter("userId"));
		Integer orgId = Integer.parseInt(req.getParameter("orgId"));
		if (userId <= 0 || orgId <= 0) {
			json.put("code", "401");
			json.put("msg", "param error");
			out.println(json);
			out.flush();
			out.close();
			return;
		}
		RelationEntity re = new RelationEntity();
		re.setUserId(userId);
		IRelationService svr = this.springCtx.getBean(IRelationService.class);
		List<RelationEntity> relationEntities = svr.getEntitiesBy(re);
		// 如果只有一条关系数据，则不能移出
		if (relationEntities != null && relationEntities.size() > 1) {
			re.setOrgId(orgId);
			svr.removeBy(re);
			json.put("code", "200");
			json.put("msg", "move out success");
			out.println(json);
			out.flush();
			out.close();
		} else {
			json.put("code", "201");
			json.put("msg", "失败，移出后该用户将没有所属部门。");
			out.println(json);
			out.flush();
			out.close();
		}

	}

	private void resetPassword(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer userId = Integer.parseInt(req.getParameter("userId"));
		UserEntity e = new UserEntity();
		e.setId(userId);
		e.setPassword(MessageDigestUtils.toMD5Hex("123456"));
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		usersvr.updatePassword(e);
		json.put("code", "200");
		json.put("msg", "reset password success");
		out.println(json);
		out.flush();
		out.close();
	}

	private void modifyPassword(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		String password = req.getParameter("password");
		LoginEntity le = (LoginEntity) req.getSession().getAttribute(Constants.SESSION_USER_ENTITY);
		UserEntity e = new UserEntity();
		e.setId(le.getUserId());
		e.setPassword(MessageDigestUtils.toMD5Hex(password));
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		usersvr.updatePassword(e);
		json.put("code", "200");
		json.put("msg", "modify password success");
		out.println(json);
		out.flush();
		out.close();
	}

	private void modifyUser(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer id = Integer.parseInt(req.getParameter("userId"));
		String trueName = req.getParameter("trueName");
		String email = req.getParameter("email");
		String remark = req.getParameter("remark");
		Integer belongOrgId = Integer.parseInt(req.getParameter("belongOrgId"));
		UserEntity e = new UserEntity(id, email, null, trueName, remark);
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		usersvr.update(e);
		RelationEntity re = new RelationEntity(id, belongOrgId);
		IRelationService relationSvr = this.springCtx.getBean(RelationService.class);
		relationSvr.update(re);
		json.put("code", "200");
		json.put("msg", "modify password success");
		out.println(json);
		out.flush();
		out.close();
	}

	private void deleteUser(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		usersvr.remove(Integer.parseInt(req.getParameter("userId")));
		json.put("code", "200");
		json.put("msg", "add user succsss");
		out.println(json);
		out.flush();
		out.close();
	}

	private void getAllUsers(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		IUserService usersvr = this.springCtx.getBean(UserService.class);
		List<UserEntity> users = usersvr.getAllUsers();
		json.put("code", "200");
		json.put("data", users);
		out.println(json);
		out.flush();
		out.close();
	}

	public void getAllUsersByOrgId(HttpServletRequest req, HttpServletResponse res) throws IOException {
		PrintWriter out = res.getWriter();
		JSONObject json = new JSONObject();
		Integer ownerId = ((LoginEntity) req.getSession().getAttribute("user")).getUserId();
		RelationService relationService = this.springCtx.getBean(RelationService.class);
		RelationEntity relationEntity = new RelationEntity();
		relationEntity.setUserId(ownerId);
		// relationEntity = relationService.getEntityBy(relationEntity);
		OrgService orgService = this.springCtx.getBean(OrgService.class);
		List<Integer> ids = new ArrayList<Integer>();
		List<RelationEntity> relationEntities = relationService.getEntitiesBy(relationEntity);
		for (RelationEntity re : relationEntities) {
			ids.add(re.getOrgId());
			queryOrd(ids, re.getOrgId(), orgService);
		}

//		List<Integer> ids = new ArrayList<Integer>();
//		Integer orgId = relationEntity.getOrgId();
//		ids.add(orgId);
//		OrgService orgService = this.springCtx.getBean(OrgService.class);
//		queryOrd(ids, orgId, orgService);
		UserService userService = this.springCtx.getBean(UserService.class);
		List<UserEntity> UserList = userService.getAllUsersByOrgId(ids);
		json.put("status", "200");
		json.put("data", UserList);
		out.println(json);
		out.flush();
		out.close();
	}

	protected void queryOrd(List<Integer> ids, Integer id, OrgService orgService) {
		OrgEntity orgEntity = new OrgEntity();
		orgEntity.setParentOrgId(id);
		List<OrgEntity> orgEntitys = orgService.getEntitiesBy(orgEntity);
		Iterator<OrgEntity> it = orgEntitys.iterator();
		while (it.hasNext()) {
			orgEntity = (OrgEntity) it.next();
			ids.add(orgEntity.getId());
			queryOrd(ids, orgEntity.getId(), orgService);
		}
	}

}
